package com.ys.service.amazonorder.impl;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import com.ys.entity.base.TbPlatform;
import com.ys.entity.base.TbSite;
import com.ys.service.amazonorder.*;
import com.ys.util.AESUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.threeten.bp.OffsetDateTime;

import com.alibaba.fastjson.JSON;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentials;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentialsProvider;
import com.amazon.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import com.bo.sellingpartnerapi.Feeds20210630.model.Feed;
import com.bo.sellingpartnerapi.Reports20210630.api.ReportsApi;
import com.bo.sellingpartnerapi.Reports20210630.model.CreateReportResponse;
import com.bo.sellingpartnerapi.Reports20210630.model.CreateReportSpecification;
import com.bo.sellingpartnerapi.Reports20210630.model.Report;
import com.bo.sellingpartnerapi.Reports20210630.model.ReportDocument;
import com.bo.sellingpartnerapi.Reports20210630.model.ReportOptions;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import com.ys.config.MyConfig;
import com.ys.entity.amazonorder.TpAmazonSellerReport;
import com.ys.entity.amazonorder.TpAmazonShopOrderOrigin;
import com.ys.entity.business.TpAmazonSeller;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.business.TpAmazonShopExchangeRate;
import com.ys.entity.sys.TbStaticConfig;
import com.ys.enume.OrderStatusType;
import com.ys.enume.RegionEnum;
import com.ys.enume.amazonorder.TpAmazonShopReportEnum;
import com.ys.mapper.amazonorder.AmazonorderMapper;
import com.ys.mapper.amazonorder.TpAmazonSellerReportMapper;
import com.ys.mapper.amazonorder.TpAmazonShopOrderOriginMapper;
import com.ys.service.sys.TbStaticConfigService;
import com.ys.util.DateUtil;

@Service("tpAmazonSellerReportService")
public class TpAmazonSellerReportServiceImpl implements TpAmazonSellerReportService {

    private static final Logger logger = LoggerFactory.getLogger(TpAmazonSellerReportServiceImpl.class);

//    private static final Logger logger = LoggerFactory.getLogger(TpAmazonShopServiceImpl.class);

	@Autowired
	private AmazonorderMapper amazonorderMapper;
	@Autowired
	private TpAmazonShopOrderOriginMapper tpAmazonShopOrderOriginMapper;
	@Autowired
	private TpAmazonSellerReportMapper tpAmazonSellerReportMapper;
	@Autowired
	private TpAmazonShopOrderService tpAmazonShopOrderService;
	@Autowired
	private TpAmazonShopOrderLatestService tpAmazonShopOrderLatestService;
	@Autowired
	private TpAmazonSellerExceptionService tpAmazonSellerExceptionService;
    @Autowired
    private TbStaticConfigService tbStaticConfigService;
    @Autowired
    private TpAmazonShopOrderDailyService tpAmazonShopOrderDailyService;
    @Autowired
    private TcoDayShopService tcoDayShopService;

	@Autowired
	private TcoRankShopByAmountRmbService tcoRankShopByAmountRmbService;
	
	
	@Override
	public void add(String sellerId, String latestUpdateDayBegin, String latestUpdateDayEnd,
			Map<String, AWSAuthenticationCredentials> MAP_REGION_Credentials,
    		AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider) {
		// 判断是否存在未解析报告
		if(new TpAmazonSellerReport().setState(TpAmazonShopReportEnum.State.NO_HANDLE.value).setSellerId(sellerId).count() > 0) {
			return;
		} else {
			TpAmazonShop tpAmazonShop = new TpAmazonShop().setSellerId(sellerId)
					.where("(A.ShopName like '%GB%' OR A.ShopName like '%US%')")
					.queryFirst();
			//查询卖家管理
			TpAmazonSeller tpAmazonSeller = new TpAmazonSeller().setSellerId(tpAmazonShop.getSellerId()).queryFirst();

			//平台
			TbPlatform tbPlatform = new TbPlatform().setCode("PTBM001").queryFirst();
			if (tbPlatform == null){
				return;
			}
			String encryptSecret = AESUtil.aesDecrypt(tbPlatform.getEncryptSecret());

			//站点信息
			TbSite tbSite = new TbSite().setId(tpAmazonShop.getSiteId()).queryFirst();
			List<String> listMarketplaceId =  new ArrayList<String>();
			if(tbSite.getAmazonMarketplaceId() != null && tbSite.getAmazonMarketplaceId().length() > 0) {
				for(String str : tbSite.getAmazonMarketplaceId().split(",")) {
					if (str != null && str.length() > 0) {
						listMarketplaceId.add(str);
					}
				}
			}
			Date startLatestUpdateTime = DateUtil.parseYYYY_MM_dd_HH_mm_ss(latestUpdateDayBegin + " 00:00:00");
			Date endLatestUpdateTime = DateUtil.parseYYYY_MM_dd_HH_mm_ss(latestUpdateDayEnd + " 23:59:59");
			String startLatestUpdateTimeStr = DateUtil.getYYYY_MM_DDTHH_mm_ssZ(startLatestUpdateTime);//amazonShop.getLastOrderSyncDate();(2023.01.29以各个调用方法时传的开始时间为准)
			String endLatestUpdateTimeStr = DateUtil.getYYYY_MM_DDTHH_mm_ssZ(endLatestUpdateTime);
	
			CreateReportSpecification body = new CreateReportSpecification();
			body.setReportType("GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL");
			body.setMarketplaceIds(listMarketplaceId);
			body.setDataStartTime(OffsetDateTime.parse(startLatestUpdateTimeStr)); // 订单最新更新时间-起
			body.setDataEndTime(OffsetDateTime.parse(endLatestUpdateTimeStr)); // 订单最新更新时间-止
			ReportOptions reportOptions = new ReportOptions();
			reportOptions.put("custom", "true");
			body.setReportOptions(reportOptions);
			
	
			//获取区域对应的端点枚举，取不到直接跳转过
			String regionCode = tbSite.getRegionCode();
			String awsRegion = RegionEnum.getAwsRegion(regionCode);
			if (awsRegion == null){
				logger.error("店铺绑定的区域对应端点枚举获取不到，请检查！");
				return;
			}
			LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
					.clientId(MyConfig.getAmazonLwaClientKey()).clientSecret(encryptSecret)
					.refreshToken(tpAmazonSeller.getRefreshToken()).endpoint(MyConfig.getAmazonLwaEndpoint()).build();
			ReportsApi reportsApi = new ReportsApi.Builder().awsAuthenticationCredentials(MAP_REGION_Credentials.get(regionCode))
					.lwaAuthorizationCredentials(lwaAuthorizationCredentials)
					.awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
					.endpoint(RegionEnum.getServiceUrl(regionCode)).build();
			CreateReportResponse reportResponse = null;
	
			try {
				// 向亚马逊请求创建报告
				reportResponse = reportsApi.createReport(body);
				if (reportResponse != null){
					String reportId = reportResponse.getReportId();
					String reportDocumentId = null;
					
					Integer state = TpAmazonShopReportEnum.State.NO_HANDLE.value;
					TpAmazonSellerReport entity = TpAmazonSellerReport.tpAmazonSellerReport(
							sellerId, reportId, reportDocumentId, regionCode, latestUpdateDayBegin, latestUpdateDayEnd, state, 1);
					tpAmazonSellerReportMapper.insert(entity);
				} else {
					tpAmazonSellerExceptionService.add(tpAmazonShop.getSellerId(), tpAmazonShop.getShopName(), "创建报告失败：报告返回空");
				}
			} catch (Exception ex){
				ex.printStackTrace();
				tpAmazonSellerExceptionService.add(tpAmazonShop.getSellerId(), tpAmazonShop.getShopName(), "创建报告失败：报告异常");
			}
		}
	}

	@Override
	public void updateReportDocumentId(Long id,
			Map<String, AWSAuthenticationCredentials> MAP_REGION_Credentials,
    		AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider) throws Exception {
		
		TpAmazonSellerReport tpAmazonShopReport = new TpAmazonSellerReport().setId(id).queryFirst();
		if (tpAmazonShopReport.getState() != TpAmazonShopReportEnum.State.NO_HANDLE.value) {
			return;
		}
		TpAmazonSeller tpAmazonShop = new TpAmazonSeller().setSellerId(tpAmazonShopReport.getSellerId()).queryFirst();
		
		String regionCode = tpAmazonShop.getRegionCode();
		//获取区域对应的端点枚举，取不到直接跳转过
		String awsRegion = RegionEnum.getAwsRegion(regionCode);
		if (awsRegion == null){
			logger.error("店铺绑定的区域对应端点枚举获取不到，请检查！");
			return;
		}

		//平台
		TbPlatform tbPlatform = new TbPlatform().setCode("PTBM001").queryFirst();
		if (tbPlatform == null){
			return;
		}
		String encryptSecret = AESUtil.aesDecrypt(tbPlatform.getEncryptSecret());
		
		LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
				.clientId(MyConfig.getAmazonLwaClientKey()).clientSecret(encryptSecret)
				.refreshToken(tpAmazonShop.getRefreshToken()).endpoint(MyConfig.getAmazonLwaEndpoint()).build();
		ReportsApi reportsApi = new ReportsApi.Builder().awsAuthenticationCredentials(MAP_REGION_Credentials.get(regionCode))
				.lwaAuthorizationCredentials(lwaAuthorizationCredentials)
				.awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
				.endpoint(RegionEnum.getServiceUrl(regionCode)).build();
		
		
		String reportDocumentId = null;
		Report report = null;
		Report.ProcessingStatusEnum processingStatus = null;
		
		// {"createdTime":{"dayOfMonth":11,"dayOfWeek":"THURSDAY","dayOfYear":131,"hour":3,"minute":25,"month":"MAY","monthValue":5,"nano":0,"offset":{"rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]},"totalSeconds":0},"second":2,"year":2023},"dataEndTime":{"dayOfMonth":11,"dayOfWeek":"THURSDAY","dayOfYear":131,"hour":11,"minute":24,"month":"MAY","monthValue":5,"nano":0,"offset":{"$ref":"$.createdTime.offset"},"second":58,"year":2023},"dataStartTime":{"dayOfMonth":10,"dayOfWeek":"WEDNESDAY","dayOfYear":130,"hour":11,"minute":24,"month":"MAY","monthValue":5,"nano":0,"offset":{"$ref":"$.createdTime.offset"},"second":58,"year":2023},"marketplaceIds":["A1F83G8C2ARO7P"],"processingEndTime":{"dayOfMonth":11,"dayOfWeek":"THURSDAY","dayOfYear":131,"hour":3,"minute":25,"month":"MAY","monthValue":5,"nano":0,"offset":{"$ref":"$.createdTime.offset"},"second":20,"year":2023},"processingStartTime":{"dayOfMonth":11,"dayOfWeek":"THURSDAY","dayOfYear":131,"hour":3,"minute":25,"month":"MAY","monthValue":5,"nano":0,"offset":{"$ref":"$.createdTime.offset"},"second":9,"year":2023},"processingStatus":"DONE","reportDocumentId":"amzn1.spdoc.1.4.eu.0e2fce8c-5aaa-4652-85f4-62f81eeed6bb.T33K43D2OKEU87.2407","reportId":"95378019488","reportType":"GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL"}
		report = reportsApi.getReport(tpAmazonShopReport.getReportId());
		processingStatus = report.getProcessingStatus();
		if (Feed.ProcessingStatusEnum.DONE.getValue().equals(processingStatus.getValue())
				|| Feed.ProcessingStatusEnum.CANCELLED.getValue().equals(processingStatus.getValue())
				|| Feed.ProcessingStatusEnum.FATAL.getValue().equals(processingStatus.getValue())) {
			reportDocumentId = report.getReportDocumentId();
			tpAmazonShopReport.setReportDocumentId(reportDocumentId);
			tpAmazonShopReport.setState(TpAmazonShopReportEnum.State.GET_REPORTED.value);
			tpAmazonSellerReportMapper.update(tpAmazonShopReport);
		}
	}

	@SuppressWarnings("resource")
	@Override
	public void finish(Long id, Map<String, TpAmazonShopExchangeRate> MAP_CODE_RATE,
			Map<String, AWSAuthenticationCredentials> MAP_REGION_Credentials,
    		AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider) throws Exception {
		
		TpAmazonSellerReport tpAmazonSellerReport = new TpAmazonSellerReport().setId(id).queryFirst();
		String sellerId = tpAmazonSellerReport.getSellerId();
		TpAmazonSeller tpAmazonShop = new TpAmazonSeller().setSellerId(tpAmazonSellerReport.getSellerId()).queryFirst();
		if (tpAmazonSellerReport.getState() != TpAmazonShopReportEnum.State.GET_REPORTED.value) {
			return;
		}
		
		String regionCode = tpAmazonShop.getRegionCode();
		//获取区域对应的端点枚举，取不到直接跳转过
		String awsRegion = RegionEnum.getAwsRegion(regionCode);
		if (awsRegion == null){
			logger.error("店铺绑定的区域对应端点枚举获取不到，请检查！");
			return;
		}

		//平台
		TbPlatform tbPlatform = new TbPlatform().setCode("PTBM001").queryFirst();
		if (tbPlatform == null){
			return;
		}
		String encryptSecret = AESUtil.aesDecrypt(tbPlatform.getEncryptSecret());
		
		// 根据店铺的refreshToken生成订单报告
		LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
				.clientId(MyConfig.getAmazonLwaClientKey()).clientSecret(encryptSecret)
				.refreshToken(tpAmazonShop.getRefreshToken()).endpoint(MyConfig.getAmazonLwaEndpoint()).build();
		ReportsApi reportsApi = new ReportsApi.Builder().awsAuthenticationCredentials(MAP_REGION_Credentials.get(regionCode))
				.lwaAuthorizationCredentials(lwaAuthorizationCredentials)
				.awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
				.endpoint(RegionEnum.getServiceUrl(regionCode)).build();

		// 获取报告文件
		ReportDocument reportDocument = reportsApi.getReportDocument(tpAmazonSellerReport.getReportDocumentId());
		if (reportDocument != null) {
			String compressionAlgorithm = (reportDocument.getCompressionAlgorithm() == null ? "":reportDocument.getCompressionAlgorithm().toString());
			OkHttpClient httpclient = new OkHttpClient();
            Request request = new Request.Builder().url(reportDocument.getUrl()).get().build();
			Response httpResponse = httpclient.newCall(request).execute();
			if (!httpResponse.isSuccessful()) {
				tpAmazonSellerExceptionService.add(tpAmazonShop.getSellerId(), tpAmazonShop.getSellerName(), "获取报告失败：发起请求失败");
				return;
			}
			try (ResponseBody responseBody = httpResponse.body()) {
				MediaType mediaType = MediaType.parse(httpResponse.header("Content-Type"));
				Charset charset = mediaType.charset();
				if (charset == null) {
					tpAmazonSellerExceptionService.add(tpAmazonShop.getSellerId(), tpAmazonShop.getSellerName(), "获取报告失败：获取媒体类型失败");
					return;
				}
				Closeable closeThis = null;
				try {
					InputStream inputStream = responseBody.byteStream();
					closeThis = inputStream;
					if ("GZIP".equals(compressionAlgorithm)) {
						inputStream = new GZIPInputStream(inputStream);
						closeThis = inputStream;
					}
					if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
						InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
						closeThis = inputStreamReader;
						BufferedReader reader = new BufferedReader(inputStreamReader);
						closeThis = reader;
						StringBuilder stringBuilder = new StringBuilder();
						String line ;
						do {
							line = reader.readLine();
							if (line != null) {
								stringBuilder.append(line).append("\n");
							}
						} while (line != null);
						
						String nowDateStr = DateUtil.getYYYY_MM_DD(new Date());
						String filePath = MyConfig.getProfile() + "/amazonreport/order/"+nowDateStr.replace("-", "");
						String fileName = "order_report_" + tpAmazonShop.getSellerId() +".txt";
						File file = new File(filePath);
						if(!file.exists()){
							file.mkdirs();
						}
						File reportFile = new File(filePath + "/"+ fileName);
						if (!reportFile.exists()){
							reportFile.createNewFile();
						}
						OutputStream outputStream = new FileOutputStream(reportFile);
						outputStream.write(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
						outputStream.close();
						BufferedReader bufferedReader = null;
						String reportLine = "";
						String separator = "\t";
						try {
							InputStreamReader inputStreamReader2 = new InputStreamReader(new FileInputStream(filePath + "/"+ fileName), StandardCharsets.UTF_8);
							bufferedReader = new BufferedReader(inputStreamReader2);
							String title = bufferedReader.readLine();
							if ("Date range exceeded. Report can be requested only upto 30 days".equals(title)){
								tpAmazonSellerExceptionService.add(tpAmazonShop.getSellerId(), tpAmazonShop.getSellerName(), "获取报告失败：范围超过30天");
								return;
							}
							String[] titleArr = title.split(separator);
							amazonorderMapper.deleteBatchTpAmazonShopOrderOriginBySeller(tpAmazonSellerReport.getSellerId());
							// 标题-序号
							Map<String, Integer> MAP_TITLE_NO = new HashMap<String, Integer>();
							for (int i = 0; i < titleArr.length; i++) {
								MAP_TITLE_NO.put(titleArr[i], i);
							}
							while ((reportLine = bufferedReader.readLine()) != null) {
								if (reportLine != null && reportLine.length() > 0) {
									//内容数组
									String[] reportEleArr = reportLine.split(separator);
									//判断内容和标题的size
									if ((reportEleArr.length) < titleArr.length) {
										int len = titleArr.length - reportEleArr.length;
										reportEleArr = Arrays.copyOf(reportEleArr, reportEleArr.length + len);
									}
									
									String amazonOrderId = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_AMAZONORDERID.code);
									String merchantOrderId = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_MERCHANTORDERID.code);
									String purchaseDate = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_PURCHASEDATE.code);
									String lastUpdateDate = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_LASTUPDATEDDATE.code);
									String orderStatus = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_ORDERSTATUS.code);
									String fulfillmentChannel = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_fulfillment_channel.code);
									String salesChannel = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_SALESCHANNEL.code);
									String orderChannel = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_order_channel.code);
									String shipServiceLevel = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_ship_service_level.code);
									String productName = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_product_name.code);
									String sku = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_SKU.code);
									String asin = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_ASIN.code);
									String itemStatus = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_item_status.code);
									String quantityStr = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_QUANTITY.code);
									Integer quantity = quantityStr != null && quantityStr.length() > 0 ? Integer.parseInt(quantityStr) : null;
									String currency = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_CURRENCY.code);
									String itemPriceStr = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_item_price.code);
									BigDecimal itemPrice = itemPriceStr != null && itemPriceStr.length() > 0 ? new BigDecimal(itemPriceStr) : null;
									String itemTaxStr = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_item_tax.code);
									BigDecimal itemTax = itemTaxStr != null && itemTaxStr.length() > 0 ? new BigDecimal(itemTaxStr) : null;
									String shippingPriceStr = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_shipping_price.code);
									BigDecimal shippingPrice = shippingPriceStr != null && shippingPriceStr.length() > 0 ? new BigDecimal(shippingPriceStr) : null;
									String shippingTaxStr = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_shipping_tax.code);
									BigDecimal shippingTax = shippingTaxStr != null && shippingTaxStr.length() > 0 ? new BigDecimal(shippingTaxStr) : null;
									String giftWrapPriceStr = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_gift_wrap_price.code);
									BigDecimal giftWrapPrice = giftWrapPriceStr != null && giftWrapPriceStr.length() > 0 ? new BigDecimal(giftWrapPriceStr) : null;
									String itemPromotionDiscount = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_item_promotion_discount.code);
									String shipPromotionDiscount = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_ship_promotion_discount.code);
									String shipCity = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_ship_city.code);
									String shipState = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_ship_state.code);
									String shipPostalCode = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_ship_postal_code.code);
									String shipCountry = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_ship_country.code);
									String promotionIds = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_promotion_ids.code);
									String isBusinessOrder = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_is_business_order.code);
									String purchaseOrderNumber = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_purchase_order_number.code);
									String priceDesignation = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_price_designation.code);
									String signatureConfirmationRecommended = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_signature_confirmation_recommended.code);
									String isIba = getDataFromArrByKey(reportEleArr, MAP_TITLE_NO, OrderStatusType.T_is_iba.code);
									TpAmazonShopOrderOrigin tpAmazonShopOrderOrigin = TpAmazonShopOrderOrigin.tpAmazonShopOrderOrigin(
											sellerId, amazonOrderId, merchantOrderId, purchaseDate, lastUpdateDate,
											orderStatus, fulfillmentChannel, salesChannel, orderChannel, shipServiceLevel,
											productName, sku, asin, itemStatus, quantity,
											currency, itemPrice, itemTax, shippingPrice, shippingTax,
											giftWrapPrice, itemPromotionDiscount, shipPromotionDiscount, shipCity,
											shipState, shipPostalCode, shipCountry, promotionIds, isBusinessOrder,
											purchaseOrderNumber, priceDesignation, signatureConfirmationRecommended, isIba, 1);
									try {
										tpAmazonShopOrderOriginMapper.insert(tpAmazonShopOrderOrigin);
									} catch (Exception e) {
										JSON.toJSONString(tpAmazonShopOrderOrigin);
									}
								}
							}
							
							// 更新状态
							tpAmazonSellerReport.setState(TpAmazonShopReportEnum.State.FINISH.value);
							tpAmazonSellerReportMapper.update(tpAmazonSellerReport);
							
							// 将原始订单数据存入最近数据
							tpAmazonShopOrderLatestService.addBatchFromOrigin(tpAmazonSellerReport.getSellerId());
							
							// 将最近数据存入订单日报表
							tpAmazonShopOrderService.addBatchFromLatest(tpAmazonSellerReport.getSellerId());
							
							// 连续更新1天内的订单日报表数据
							Date now = new Date();
							for (int i = 13; i >= 0; i--) {
								String day = DateUtil.getYYYY_MM_DD(DateUtil.addDays(now, i * -1));
								
								// 添加商品日报表数据
								tpAmazonShopOrderDailyService.addBatchBySeller(day, sellerId);
								
								// 更新商品日报表统计数据
								tpAmazonShopOrderDailyService.updateCountByDayAndSeller(day, sellerId);
							}
							
							// 后续操作
							finishAll(1);
						} catch (Exception ex){
							ex.printStackTrace();
							tpAmazonSellerExceptionService.add(tpAmazonShop.getSellerId(), tpAmazonShop.getSellerName(), "获取报告失败：解析数据出错1");
						}
					}
				} catch (Exception ex){
					ex.printStackTrace();
					tpAmazonSellerExceptionService.add(tpAmazonShop.getSellerId(), tpAmazonShop.getSellerName(), "获取报告失败：解析数据出错2");
				} finally {
					if (closeThis != null) {
						closeThis.close();
					}
				}
			}
		}
	}
	
	private String getDataFromArrByKey(String[] reportEleArr, Map<String, Integer> MAP_TITLE_NO, String key){
		if (MAP_TITLE_NO.containsKey(key)) {
			return reportEleArr[MAP_TITLE_NO.get(key)];
		} else {
			return null;
		}
	}

	@Override
	public void finishAll(Integer type) {
		Thread t = new Thread(() -> {
			if (type == 1) {
				if(new TpAmazonSellerReport().where("A.state in (0,1)").count() > 0) {
					return;
				}
			}
			
			// 强行完成，需判断最新更新时间在两小时内
			if (type == 2) {
				Date now = new Date();
				TbStaticConfig entity = new TbStaticConfig()
						.setKeyOne("refresh-amazon-shop-order")
						.setKeyTwo("finishi-time")
						.queryFirst();
				if (entity.getName().compareTo(DateUtil.getYYYY_MM_DD_HH_mm_ss(DateUtil.addSecond(now, -7200))) > 0) {
					return;
				}
			}
			
			System.out.println("刷新店铺订单的更新截止时间【start】---------" + new Date());
			tbStaticConfigService.updateRefreshAmazonOrderFinishiTime();
			
			// 删除两天前的报告记录
			String createTimeMax = DateUtil.getYYYY_MM_DD(DateUtil.addDays(new Date(), -2)) + " 00:00:00";
			amazonorderMapper.deleteBatchTpAmazonSellerReport(createTimeMax);
			
			// 添加店铺每日统计(近14天)
			Date now = new Date();
			for (int i = 13; i >= 0; i--) {
				String day = DateUtil.getYYYY_MM_DD(DateUtil.addDays(now, i * -1));
				
				tcoDayShopService.addAndUpdateTcoDayShop(day);
			}
			
			// 
			tpAmazonShopOrderService.notify1_5_TO_DO_COUNT();
			
			tpAmazonShopOrderService.notify1_5_TO_DO_ANALYSIS();

			tcoRankShopByAmountRmbService.addTcoRankShopByAmountRmb();
			System.out.println("刷新店铺订单的更新截止时间【end】---------" + new Date());
		});
		t.start();
	}
}
